package com.wh.wisdomsite.xbox.server.task.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.wh.wisdomsite.xbox.du.entity.DustDevRecord;
import com.wh.wisdomsite.xbox.du.entity.DustProCheckPoint;
import com.wh.wisdomsite.xbox.du.service.IDustDevRecordService;
import com.wh.wisdomsite.xbox.du.service.IDustProCheckPointService;
import com.wh.wisdomsite.xbox.me.entity.CraneProject;
import com.wh.wisdomsite.xbox.me.entity.CraneRecord;
import com.wh.wisdomsite.xbox.me.service.ICraneProjectService;
import com.wh.wisdomsite.xbox.me.service.ICraneRecordService;
import com.wh.wisdomsite.xbox.server.task.interFace.CollectHistoryData;
import com.wh.wisdomsite.xbox.server.util.WebUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 获取设备历史数据实现类
 *
 * @version V1.0
 * @Package: com.wh.wisdomsite.xbox.server.task.impl
 * @author: 丁奕
 * @date: 2018-09-29 10:27
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 **/
@Service
public class CollectHistoryDataImpl implements CollectHistoryData {

    @Autowired
    ICraneProjectService iCraneProjectService;

    @Autowired
    ICraneRecordService iCraneRecordService;

    @Autowired
    IDustProCheckPointService iDustProCheckPointService;

    @Autowired
    IDustDevRecordService iDustDevRecordService;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void collectData() {
        //获取所有的起重机械设备
        EntityWrapper<CraneProject> craneProjectEntityWrapper = new EntityWrapper<>();
        craneProjectEntityWrapper.setEntity(new CraneProject());
        List<CraneProject> craneProjectList = iCraneProjectService.selectList(craneProjectEntityWrapper);

        //获取所有的扬尘设备
        EntityWrapper<DustProCheckPoint> dustProCheckPointEntityWrapper = new EntityWrapper<>();
        dustProCheckPointEntityWrapper.setEntity(new DustProCheckPoint());
        List<DustProCheckPoint> dustProCheckPoints = iDustProCheckPointService.selectList(dustProCheckPointEntityWrapper);

        //获取时间，生成查询时间参数
        Calendar now = Calendar.getInstance();
        String today = now.get(Calendar.YEAR)+"-"+(now.get(Calendar.MONTH) + 1)+"-"+now.get(Calendar.DAY_OF_MONTH);
        now.setTime(new Date(now.getTimeInMillis() - 60 * 60 * 24 * 1000));
        String lastDay = now.get(Calendar.YEAR)+"-"+(now.get(Calendar.MONTH) + 1)+"-"+now.get(Calendar.DAY_OF_MONTH);
        //设置起重机械和扬尘要查询的参数
        String dustLabels = "pm25,pm10,wd,tmp,rh,zs";
        String craneLabels = "Angle,Radius,Height,LoadData,Safeload,MomentPercent,WindSpeed,ObliqueAngle,ObliqueDirection,Fall";
        //遍历扬尘设备，生成前一天的均值历史数据
        for (DustProCheckPoint dustProCheckPoint : dustProCheckPoints){
            String deviceId = dustProCheckPoint.getDeviceId();
            //判断前一天该设备是否已有数据
            EntityWrapper<DustDevRecord> dustDevRecordEntityWrapper = new EntityWrapper<>();
            dustDevRecordEntityWrapper.setEntity(new DustDevRecord());
            dustDevRecordEntityWrapper.eq("dpcpId", dustProCheckPoint.getDpcpId());
            dustDevRecordEntityWrapper.between("collectTime",lastDay,today);
            List<DustDevRecord> dustDevRecords = iDustDevRecordService.selectList(dustDevRecordEntityWrapper);
            if(dustDevRecords != null && !dustDevRecords.isEmpty()){
                continue;
            }
            //拼接好查询url
            String url = "http://store.d.guijianyun.com:8000/devices/"+deviceId+"/avg?start="+
                    lastDay+"&end="+today+"&labels="+dustLabels;
            JSONObject jsonObject = null;
            //进行查询
            try {
                String result = WebUtil.getMessageFromUrl(url);
                jsonObject = JSONObject.fromObject(result);
            }catch (Exception e){
                continue;
            }
            //根据返回结果进行插入历史数据操作
            if(jsonObject != null){
                jsonObject = jsonObject.getJSONObject("values");
                if(jsonObject == null || jsonObject.size() == 0){
                    continue;
                }
                try {
                    DustDevRecord dustDevRecord = new DustDevRecord();
                    double pm25 = getDouble(jsonObject,"pm25");
                    double pm10 = getDouble(jsonObject,"pm10");
                    dustDevRecord.setDdrId(UUID.randomUUID().toString().replace("-",""));
                    dustDevRecord.setCollectTime(simpleDateFormat.parse(lastDay+" 01:00:00"));
                    dustDevRecord.setDpcpId(dustProCheckPoint.getDpcpId());
                    dustDevRecord.setHumidity(getDouble(jsonObject,"rh"));
                    dustDevRecord.setNoise(getDouble(jsonObject,"zs"));
                    dustDevRecord.setPm10(pm10);
                    dustDevRecord.setPm25(pm25);
                    dustDevRecord.setTemperature(getDouble(jsonObject,"tmp"));
                    dustDevRecord.setWindSpeed(getDouble(jsonObject,"wd"));
                    dustDevRecord.setAqi(calcAqi(pm25));
                    iDustDevRecordService.insert(dustDevRecord);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        //遍历起重机械设备，生成前一天的均值历史数据
        for (CraneProject craneProject : craneProjectList){
            String deviceId = craneProject.getDeviceId();
            //判断前一天该设备是否已有数据
            EntityWrapper<CraneRecord> craneRecordEntityWrapper = new EntityWrapper<>();
            craneRecordEntityWrapper.setEntity(new CraneRecord());
            craneRecordEntityWrapper.eq("cpId", craneProject.getCpId());
            craneRecordEntityWrapper.between("collectTime",lastDay,today);
            List<CraneRecord> craneRecords = iCraneRecordService.selectList(craneRecordEntityWrapper);
            if(craneRecords != null && !craneRecords.isEmpty()){
                continue;
            }
            //拼接好查询url
            String url = "http://store.d.guijianyun.com:8000/devices/"+deviceId+"/avg?start="+
                    lastDay+"&end="+today+"&labels="+craneLabels;
            JSONObject jsonObject = null;
            //进行查询
            try {
                String result = WebUtil.getMessageFromUrl(url);
                jsonObject = JSONObject.fromObject(result);
            }catch (Exception e){
                continue;
            }
            //根据返回结果进行插入历史数据操作
            if(jsonObject != null){
                jsonObject = jsonObject.getJSONObject("values");
                if(jsonObject == null || jsonObject.size() == 0){
                    continue;
                }
                try {
                    CraneRecord craneRecord = new CraneRecord();
                    craneRecord.setCrId(UUID.randomUUID().toString().replace("-",""));
                    craneRecord.setCollectTime(simpleDateFormat.parse(lastDay+" 01:00:00"));
                    craneRecord.setCpId(craneProject.getCpId());
                    craneRecord.setTorque(new BigDecimal(getDouble(jsonObject,"MomentPercent")));
                    craneRecord.setLoad(new BigDecimal(getDouble(jsonObject,"LoadData")));
                    craneRecord.setWindSpeed(new BigDecimal(getDouble(jsonObject,"WindSpeed")));
                    craneRecord.setRange(new BigDecimal(getDouble(jsonObject,"Radius")));
                    craneRecord.setHeight(new BigDecimal(getDouble(jsonObject,"Height")));
                    craneRecord.setSlewingSpeed(new BigDecimal(getDouble(jsonObject,"Angle")));
                    craneRecord.setRate(!jsonObject.get("Fall").equals("null") ? (int)jsonObject.get("Fall"):0);
                    craneRecord.setDipAngle(new BigDecimal(getDouble(jsonObject,"ObliqueAngle")));
                    iCraneRecordService.insert(craneRecord);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    private double getDouble(JSONObject jsonObject,String name) {
        if(jsonObject.get(name) instanceof Double){
            return (double)jsonObject.get(name);
        }else if(jsonObject.get(name) instanceof Integer){
            return !jsonObject.get(name).equals("null") ? (int)jsonObject.get(name) * 1.0:0.0;
        }
        return 0.0;
    }

    private double calcAqi(double pm25){
        int[] ti = {0, 50, 100, 150, 200, 300, 400, 500};
        int[] tv = {0, 35, 75, 115, 150, 250, 350, 500};

        double i = 0;
        for (int j = 0; j < tv.length; j++) {
            if (pm25 < tv[j]) {
                break;
            }
            i = i + 1;
            if (i == 7)
                return 600;
        }
        i = pm25/tv[(int)i]*ti[(int)i];
        return i;
    }
}
